package edu.nf.takeoutdemo.service.impl;

import edu.nf.takeoutdemo.mapper.OrderMapper;
import edu.nf.takeoutdemo.mapper.UserMapper;
import edu.nf.takeoutdemo.model.dto.GoodsSalesDTO;
import edu.nf.takeoutdemo.model.entity.Orders;
import edu.nf.takeoutdemo.model.vo.*;
import edu.nf.takeoutdemo.service.ReportService;
import edu.nf.takeoutdemo.service.WorkSpaceService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author zjl
 * @date 2025/11/4
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ReportServiceImpl implements ReportService {
    private final OrderMapper orderMapper;
    private final UserMapper userMapper;
    private final WorkSpaceService workSpaceService;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于begin到end范围内的每天的日期
        List<LocalDate> dateList = dateList(begin, end);
        //存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询date日期对应的营业额，营业额是指，状态为已完成的订单金额合计
            Map<String,Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 :turnover;
            turnoverList.add(turnover);
        }

        String date = StringUtil.join(",", dateList);
        TurnoverReportVO turnoverStatistics = new TurnoverReportVO();
        String turnover = StringUtil.join(",", turnoverList);
        turnoverStatistics.setDateList(date);
        turnoverStatistics.setTurnoverList(turnover);
        return turnoverStatistics;
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //存放begin到end之间的每天对应的日期
        List<LocalDate> dateList = dateList(begin, end);
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);
            Map<String,Object> map = new HashMap<>();
            map.put("end", endTime);
            Integer totalUserCount = userMapper.countByMap(map);
            map.put("begin", beginTime);
            Integer newUserCount =  userMapper.countByMap(map);
            totalUserList.add(totalUserCount);
            newUserList.add(newUserCount);
        }
        String date = StringUtil.join(",", dateList);
        String totalUser = StringUtil.join(",", totalUserList);
        String newUser = StringUtil.join(",", newUserList);
        UserReportVO userStatistics = new UserReportVO();
        userStatistics.setDateList(date);
        userStatistics.setTotalUserList(totalUser);
        userStatistics.setNewUserList(newUser);
        return userStatistics;
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = dateList(begin, end);
        //存放每天订单总数
        List<Integer> orderCountList = new ArrayList<>();
        //存放每天有效订单数
        List<Integer> validOrderList = new ArrayList<>();
        for(LocalDate date : dateList){
            //查询每天订单总数
            LocalDateTime beginTime = LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            //查询每天有效订单数
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            orderCountList.add(orderCount);
            validOrderList.add(validOrderCount);
        }
        //计算时间区间内的订单总数量
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //计算时间区间内的有效订单数量
        Integer validOrderCount = validOrderList.stream().reduce(Integer::sum).get();
        //计算订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        String date = StringUtil.join(",", dateList);
        String totalOrder = StringUtil.join(",", orderCountList);
        String validOrder = StringUtil.join(",", validOrderList);
        OrderReportVO orderStatistics = new OrderReportVO();
        orderStatistics.setDateList(date);
        orderStatistics.setOrderCountList(totalOrder);
        orderStatistics.setValidOrderCountList(validOrder);
        orderStatistics.setTotalOrderCount(totalOrderCount);
        orderStatistics.setValidOrderCount(validOrderCount);
        orderStatistics.setOrderCompletionRate(orderCompletionRate);
        return orderStatistics;
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(begin,LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).toList();
        String nameList = StringUtil.join(",", names);
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).toList();
        String numberList = StringUtil.join(",", numbers);
        SalesTop10ReportVO salesTop10Report = new SalesTop10ReportVO();
        salesTop10Report.setNameList(nameList);
        salesTop10Report.setNumberList(numberList);
        return salesTop10Report;
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {

        //查询数据库，获取营业数据 -- 最近30天
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime dateTimeBegin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime dateTimeEnd = LocalDateTime.of(dateEnd, LocalTime.MAX);
        //查询概览数据
        BusinessDataVO businessData = workSpaceService.getBusinessData(dateTimeBegin, dateTimeEnd);
        //通过POI将数据写到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue("时间："+dateBegin +"至"+dateEnd);

            XSSFRow row =  sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());


            for (int i =0;i<30;i++){
                LocalDate date = LocalDate.now().plusDays(i);
                BusinessDataVO orderData  = workSpaceService.getBusinessData(dateTimeBegin,dateTimeEnd);
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date);
                row.getCell(2).setCellValue(orderData.getTurnover());
                row.getCell(3).setCellValue(orderData.getValidOrderCount());
                row.getCell(4).setCellValue(orderData.getOrderCompletionRate());
                row.getCell(5).setCellValue(orderData.getUnitPrice());
                row.getCell(6).setCellValue(orderData.getNewUsers());
            }

            //通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            outputStream.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end,Integer status) {
        Map<String,Object> map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.countByMap(map);
    }

    /**
     * 存放begin到end之间的每天对应的日期
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> dateList(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }
}
